package com.example.app.manager.giftplay

import android.content.Context
import android.net.http.HttpResponseCache
import android.view.View
import androidx.core.view.isVisible
import androidx.multidex.BuildConfig
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.LogUtils
import com.opensource.svgaplayer.SVGACallback
import com.opensource.svgaplayer.SVGADrawable
import com.opensource.svgaplayer.SVGAImageView
import com.opensource.svgaplayer.SVGAParser
import com.opensource.svgaplayer.SVGASoundManager
import com.opensource.svgaplayer.SVGAVideoEntity
import com.opensource.svgaplayer.utils.log.SVGALogger
import java.io.File
import java.io.FileInputStream
import java.net.URL


/**
 * svga播放器
 */
object SvgaManager {

    private val TAG = SvgaManager::class.java.simpleName

    /**
     * 初始化svga
     */
    fun initSvga(context: Context) {
        SVGAParser.shareParser().init(context)
        SVGASoundManager.init()
        val cacheDir = File("${context.applicationContext.cacheDir}/svga/cache", "http")
        HttpResponseCache.install(cacheDir, 1024 * 1024 * 128)
        SVGALogger.setLogEnabled(BuildConfig.DEBUG)
    }

    /**
     * 播放svga动画，view，assets指定目录的svga文件，动态变更实体类
     *
     * 注意生命周期结束时，关闭播放
     */
    fun decodeFromAssets(svgaImg: SVGAImageView?, svgaFileName: String?, onPlayFinish: ((code: Int, msg: String) -> Unit)? = null) {
        if (svgaImg == null || svgaFileName == null || svgaImg.isAnimating) {
            val msg = "decodeFromAssets svgaFileName=$svgaFileName,isAnimating=${svgaImg?.isAnimating}"
            if (svgaImg?.isAnimating == false) {
                LogUtils.eTag(TAG, msg)
            }
            onPlayFinish?.invoke(-1, msg)
            return
        }
        try {
            SVGAParser.shareParser().decodeFromAssets(svgaFileName, object : SVGAParser.ParseCompletion {
                override fun onComplete(videoItem: SVGAVideoEntity) {
                    startPlay(svgaImg, SVGADrawable(videoItem), onPlayFinish)
                }

                override fun onError() {
                    val msg = "play error from decodeFromAssets"
                    LogUtils.eTag(TAG, msg)
                    onPlayFinish?.invoke(-1, msg)
                }
            })

        } catch (e: Exception) {
            e.printStackTrace()
            val msg = "decodeFromAssets ${e.message}"
            onPlayFinish?.invoke(-1, msg)
        }
    }

    fun decodeFromFile(svgaImg: SVGAImageView?, filePath: String?, cacheKey: String, onPlayFinish: ((code: Int, msg: String) -> Unit)? = null) {
        if (svgaImg == null || filePath.isNullOrEmpty() || !FileUtils.isFileExists(filePath) || svgaImg.isAnimating) {
            val msg = "decodeFromFile filePath=$filePath,isAnimating=${svgaImg?.isAnimating}"
            if (svgaImg?.isAnimating == false) {
                LogUtils.eTag(TAG, msg)
            }
            onPlayFinish?.invoke(-1, msg)
            return
        }
        try {
            SVGAParser.shareParser().decodeFromInputStream(FileInputStream(filePath), cacheKey, object : SVGAParser.ParseCompletion {
                override fun onComplete(videoItem: SVGAVideoEntity) {
                    startPlay(svgaImg, SVGADrawable(videoItem), onPlayFinish)
                }

                override fun onError() {
                    val msg = "play error from decodeFromFile=$filePath"
                    LogUtils.eTag(TAG, msg)
                    onPlayFinish?.invoke(-1, msg)
                }
            })
        } catch (e: Exception) {
            e.printStackTrace()
            val msg = "decodeFromFile ${e.message}"
            onPlayFinish?.invoke(-1, msg)
        }
    }

    /**
     * 加载网络SVGA
     *
     * 注意生命周期结束时，关闭播放
     *
     * 自己默认会缓存
     */
    fun decodeFromURL(svgaImg: SVGAImageView?, url: String?, onPlayFinish: ((code: Int, msg: String) -> Unit)? = null) {
        if (svgaImg == null || url.isNullOrEmpty() || (!url.startsWith("http://") && !url.startsWith("https://")) || svgaImg.isAnimating) {
            val msg = "decodeFromURL url=$url,isAnimating=${svgaImg?.isAnimating}"
            if (svgaImg?.isAnimating == false) {
                LogUtils.eTag(TAG, msg)
            }
            onPlayFinish?.invoke(-1, msg)
            return
        }
        try {
            SVGAParser.shareParser().decodeFromURL(URL(url), object : SVGAParser.ParseCompletion {
                override fun onComplete(videoItem: SVGAVideoEntity) {
                    startPlay(svgaImg, SVGADrawable(videoItem), onPlayFinish)
                }

                override fun onError() {
                    val msg = "play error from decodeFromURL=$url"
                    LogUtils.eTag(TAG, msg)
                    onPlayFinish?.invoke(-1, msg)
                }
            })

        } catch (e: Exception) {
            e.printStackTrace()
            val msg = "${e.message}"
            onPlayFinish?.invoke(-1, msg)
        }
    }

    private fun startPlay(svgaImg: SVGAImageView, svgaDrawable: SVGADrawable, onPlayFinish: ((code: Int, msg: String) -> Unit)?) {
        svgaImg.apply {
            LogUtils.dTag(TAG, "startPlay")
            isVisible = true
            if (onPlayFinish != null) {
                callback = object : SVGACallback {
                    override fun onFinished() {
                        LogUtils.dTag(TAG, "$svgaImg onFinished")
                        onPlayFinish.invoke(0, "")
                    }

                    override fun onPause() {
                        LogUtils.dTag(TAG, "onPause")
                    }

                    override fun onRepeat() {
                        //LogUtils.dTag(TAG, "$svgaImg onRepeat")
                    }

                    override fun onStep(frame: Int, percentage: Double) {
                        //LogUtils.dTag(TAG, "onStep,frame=$frame,percentage=$percentage")
                    }
                }
            }
            setImageDrawable(svgaDrawable)
            startAnimation()
        }
    }

    /**
     * 停止播放
     */
    fun stopPlay(svgaImg: SVGAImageView?, isClear: Boolean = true, isSetGone: Boolean = true) {
        svgaImg?.apply {
            callback = null
            stopAnimation(isClear)
            if (isClear) clear()
            if (isSetGone) visibility = View.GONE
        }
    }

    //清除缓存
    fun clearCache() {
        SVGASoundManager.release()
    }

}